package com.immac.chan.util;

public class ByteProcessor {
	public static byte[] toBytes(byte b) {
		byte[] bytes = new byte[] { b };
		return bytes;
	}

	public static byte[] toBytes(short s) {
		byte[] bytes = new byte[2];
		bytes[0] = (byte)(s >> (Byte.SIZE * 1)) ;
		bytes[1] = (byte)(s >> (Byte.SIZE * 0));
		return bytes;
	}

	public static byte[] toBytes(char c) {
		byte[] bytes = new byte[2];
		bytes[0] = (byte)(c >> (Byte.SIZE * 1));
		bytes[1] = (byte)(c >> (Byte.SIZE * 0)) ;
		return bytes;
	}

	public static byte[] toBytes(int iValue) {
		int size = (Integer.SIZE / Byte.SIZE) - 1;
		byte[] bytes = new byte[size + 1];
		
		for (int i = 0; i <= size; i++) {
			bytes[i] = (byte)(iValue >> (Byte.SIZE * (size - i)));
		}
		
		return bytes;
	}

	public static byte[] toBytes(float fValue) {
		int i = Float.floatToIntBits(fValue);
		return toBytes(i);
	}

	public static byte[] toBytes(long lValue) {
		int size = (Long.SIZE / Byte.SIZE) - 1;
		byte[] bytes = new byte[size + 1];
		
		for (int i = 0; i <= size; i++) {
			bytes[i] = (byte)(lValue >> (Byte.SIZE * (size - i)));
		}
		
		return bytes;
	}

	public static byte[] toBytes(double dValue) {
		long l = Double.doubleToLongBits(dValue);
		return toBytes(l);
	}
	
	public static byte toByte(byte[] bytes, int fromIndex) {
		byte b = bytes[0];
		return b;
	}

	public static short toShort(byte[] bytes, int fromIndex) {
		short result = 0;
		int size = (Short.SIZE / Byte.SIZE) - 1;
		
		for (int i = 0; i <= size; i++) {
			result += ((short)(bytes[fromIndex + i] & 255) << (Byte.SIZE * (size - i)));
		}
		
		return result;
	}

	public static char toChar(byte[] bytes, int fromIndex) {
		char result = 0;
		int size = (Character.SIZE / Byte.SIZE) - 1;
		
		for (int i = 0; i <= size; i++) {
			result += ((char)(bytes[fromIndex + i] & 255) << (Byte.SIZE * (size - i)));
		}
		
		return result;
	}

	public static int toInt(byte[] bytes, int fromIndex) {
		int result = 0;
		int size = (Integer.SIZE / Byte.SIZE) - 1;
		
		for (int i = 0; i <= size; i++) {
			result += ((int)(bytes[fromIndex + i] & 255) << (Byte.SIZE * (size - i)));
		}
		
		return result;
	}
	
	public static float toFloat(byte[] bytes, int fromIndex) {
		int i = toInt(bytes, fromIndex);
		return Float.intBitsToFloat(i);
	}

	public static long toLong(byte[] bytes, int fromIndex) {
		long result = 0;
		int size = (Long.SIZE / Byte.SIZE) - 1;
		
		for (int i = 0; i <= size; i++) {
			result += ((long)(bytes[fromIndex + i] & 255) << (Byte.SIZE * (size - i)));
		}
		
		return result;
	}
	
	public static double toDouble(byte[] bytes, int fromIndex) {
		long l = toLong(bytes, fromIndex);
		return Double.longBitsToDouble(l);
	}
}
